package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import com.huaweicloud.sdk.iotda.v5.model.AuthInfo;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.util.DateTimeZoneConverter;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 设备管理Service业务层处理
 *
 * @author syl
 * @date 2025-06-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient ioTDAClient;

    @Autowired
    private RedisTemplate<String,String>  redisTemplate;

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }




    @Override
    public void syncProductList() {
        // 从IOT平台上获取产品
       ListProductsRequest request = new ListProductsRequest();
       request.setLimit(50);
        ListProductsResponse response = ioTDAClient.listProducts(request);

        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("IOT数据同步失败");
        }

        List<ProductSummary> products = response.getProducts();
        // 存到Redis中

        redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).set(JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        String s = redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).get();
        if (s!=null) {
            List<ProductVo> productVos = JSONUtil.toList(s, ProductVo.class);
            return productVos;
        }
        return List.of();
    }

    @Override
    public void register(DeviceDto dto) {
        // 查询设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName,dto.getDeviceName());
        if (this.count(queryWrapper)>0) {
            throw new BaseException("设备名称重复");
        }

        // 查询设备标识是否重复
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getNodeId,dto.getNodeId());
        if (this.count(queryWrapper)>0) {
            throw new BaseException("设备标识重复");
        }

        // 查询同一个位置是否绑定了相同的产品
        //设备类型   具体位置  productKey
        queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getLocationType,dto.getLocationType());
        queryWrapper.eq(Device::getBindingLocation,dto.getBindingLocation());
        queryWrapper.eq(Device::getProductKey,dto.getProductKey());
        if (this.count(queryWrapper)>0) {
            throw new BaseException("同一个位置绑定了相同的产品");
        }

        // 调用IOT接口注册设备（注意设备deviceSecret需要自己生成）
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        // body.setDeviceId(""); //IOT自动生成的
        body.setNodeId(dto.getNodeId());
        body.setDeviceName(dto.getDeviceName());
        body.setProductId(dto.getProductKey());
        AuthInfo authInfo = new AuthInfo(); //秘钥
        String secret = RandomUtil.randomString(32);
        authInfo.setSecret(secret); //秘钥
        body.setAuthInfo(authInfo);
        body.setDescription(dto.getDeviceDescription());
        request.setBody(body);
        AddDeviceResponse response = ioTDAClient.addDevice(request);
        if (response.getHttpStatusCode()!=201) {
            throw new BaseException("IOT设备添加失败");
        }
        String deviceId = response.getDeviceId();

        // 本地存储设备
        Device device = BeanUtil.toBean(dto, Device.class);
        // device.setId(0L);
        device.setIotId(deviceId);  //设备id 是IOT返回的
        device.setSecret(secret);

        this.save(device);

    }

    @Override
    public DeviceDetailVo deviceDetail(String iotId) {
        // IOT查询
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = ioTDAClient.showDevice(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("IOT设备查询失败");
        }
        // 本地查询
        Device device = this.getOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId,iotId));
        if (device==null) {
            throw new BaseException("设备不存在");
        }

        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        // 2025-06-01T08:24:24.349Z
        // 把字符串转成LocalDateTime
        LocalDateTime parse = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
        LocalDateTime activeTime = DateTimeZoneConverter.utcToShanghai(parse);
        deviceDetailVo.setActiveTime(activeTime);



        return deviceDetailVo;
    }

    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        List<DeviceDataVo> list = new ArrayList<>();


        // IOT查询数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = ioTDAClient.showDeviceShadow(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("IOT设备查询失败");
        }

        List<DeviceShadowData> shadowList = response.getShadow();
        if(CollUtil.isNotEmpty(shadowList)){



            DeviceShadowData deviceShadowData = shadowList.get(0);
            DeviceShadowProperties reported = deviceShadowData.getReported();
            String eventTimeStr = reported.getEventTime();//20250601 T 08 24 34 Z
            LocalDateTime eventTimeUTC = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeUTC);

            Object properties = reported.getProperties();
            JSONObject jsonObject = JSONUtil.parseObj(properties);
            jsonObject.forEach((key,value)->{
                DeviceDataVo deviceDataVo = new DeviceDataVo();
                deviceDataVo.setFunctionId(key);
                deviceDataVo.setEventTime(eventTime);
                deviceDataVo.setValue(value);
                list.add(deviceDataVo);
            });
        }
        return list;
    }
    /**
     * 查看指定的产品
     */
    @Override
    public List queryProduct(String productKey){
        ShowProductRequest request =new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = ioTDAClient.showProduct(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("IOT产品查询失败");
        }
       return response.getServiceCapabilities();

    }

}
